﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Administration;
using PeopleEditor;

namespace PeopleEditorMenu.Layouts.PeopleEditorMenu
{
    public partial class PeoplePickerAdmin : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        #region Protected properties
        //protected WebApplicationSelector Selector1;
        //protected CheckBoxList cblSelectionSetCommon;
        //protected CheckBoxList cblSelectionSetElevated;
        //protected Label lblErrorMessage;
        //protected RadioButtonList rblAdminType;
        //protected Button BtnOK;
        //protected RadioButtonList rblOnlySearchWithinSiteCollection;
        #endregion

        #region Private fields
        private PeoplePickerSettings _commonSettings;
        private PeoplePickerSettings _adminSettings;
        #endregion

        #region Private properties
        /// <summary>
        /// Gets the current selected web application
        /// </summary>
        private SPWebApplication currentWebApplication
        {
            get
            {
                return this.Selector.CurrentItem;
            }
        }

        /// <summary>
        /// Gets if the feature is deployed to the web application
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        private bool featureDeployed(SPWebApplication webApp)
        {
            bool isDeployed = false;

            SPFeatureCollection features = webApp.Features;
            foreach (SPFeature feature in features)
            {
                if (feature.DefinitionId == Globals.FeatureID)
                {
                    isDeployed = true;
                    break;
                }
            }

            return isDeployed;
        }
        #endregion

        #region Protected methods
        /// <summary>
        /// On load of the page, a list of web applications is generated and displayed in a grid.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            lblErrorMessage.Visible = false;

            if (!IsPostBack)
            {
                this.OnContextChange(null, null);
                initializeControls();
            }
        }

        /// <summary>
        /// On prerender, the controls are updated with stored values.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (!IsPostBack)
            {
                if (!featureDeployed(this.currentWebApplication))
                {
                    featureNotLoaded();
                }
                else
                {
                    loadStoredSettings();
                    setControlValuesFromStoredSettings();
                }
            }
        }

        /// <summary>
        /// Is triggered when the web application selection changes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnContextChange(object sender, EventArgs e)
        {
            if (this.currentWebApplication != null)
            {
                initializeControls();
            }
        }

        /// <summary>
        /// Saves the settings for the currently selected webapplication
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        protected void BtnOK_Click(object sender, EventArgs args)
        {
            loadStoredSettings();

            _commonSettings.SelectionSet = Common.CreateStringFromSelections(cblSelectionSetCommon.Items);
            Common.UpdatePersistentObject(this.currentWebApplication, _commonSettings);

            _adminSettings.SelectionSet = Common.CreateStringFromSelections(cblSelectionSetElevated.Items);
            PeoplePickerSettings.AdminType type = PeoplePickerSettings.AdminType.SiteAdmin;
            if (Enum.IsDefined(typeof(PeoplePickerSettings.AdminType), rblAdminType.SelectedValue))
            {
                type = (PeoplePickerSettings.AdminType)Enum.Parse(typeof(PeoplePickerSettings.AdminType), rblAdminType.SelectedValue);
            }
            _adminSettings.TypeOfAdmin = type;
            Common.UpdatePersistentObject(this.currentWebApplication, _adminSettings);

            //Update web application general settings
            this.currentWebApplication.PeoplePickerSettings.OnlySearchWithinSiteCollection = Convert.ToBoolean(rblOnlySearchWithinSiteCollection.SelectedValue);
            this.currentWebApplication.Update();
        }
        #endregion

        #region Private methods
        /// <summary>
        /// Initialize settings
        /// </summary>
        private void initializeControls()
        {
            loadSelectionSetItems();
            loadAdminTypes();
        }

        /// <summary>
        /// Loads the SelectionSet items in the check box lists
        /// </summary>
        private void loadSelectionSetItems()
        {
            this.cblSelectionSetCommon.DataSource = Enum.GetNames(typeof(PeopleEditor.CustPeopleFind.AccountType));
            this.cblSelectionSetCommon.DataBind();

            this.cblSelectionSetElevated.DataSource = Enum.GetNames(typeof(PeopleEditor.CustPeopleFind.AccountType));
            this.cblSelectionSetElevated.DataBind();
        }

        /// <summary>
        /// Loads the admin types in the radio button list
        /// </summary>
        private void loadAdminTypes()
        {
            this.rblAdminType.Items.Clear();

            ListItem adminType = new ListItem("Site admin", PeoplePickerSettings.AdminType.SiteAdmin.ToString());
            this.rblAdminType.Items.Add(adminType);

            adminType = new ListItem("Web admin", PeoplePickerSettings.AdminType.WebAdmin.ToString());
            this.rblAdminType.Items.Add(adminType);
        }

        /// <summary>
        /// Loads the stored settings
        /// </summary>
        private void loadStoredSettings()
        {
            _commonSettings = Common.CommonPeoplePickerSettings(this.currentWebApplication);
            _adminSettings = Common.AdminPeoplePickerSettings(this.currentWebApplication);
        }

        /// <summary>
        /// Sets the control values to the ones stored in the persistent objects
        /// </summary>
        private void setControlValuesFromStoredSettings()
        {
            rblOnlySearchWithinSiteCollection.SelectedValue = this.currentWebApplication.PeoplePickerSettings.OnlySearchWithinSiteCollection.ToString().ToLower();

            string[] SelectionSet = _commonSettings.SelectionSet.Split(Globals.Delimiter);
            foreach (string Selection in SelectionSet)
            {
                foreach (ListItem item in cblSelectionSetCommon.Items)
                {
                    if (item.Value == Selection)
                    {
                        item.Selected = true;
                    }
                }
            }

            this.rblAdminType.SelectedValue = _adminSettings.TypeOfAdmin.ToString();
            SelectionSet = _adminSettings.SelectionSet.Split(Globals.Delimiter);
            foreach (string Selection in SelectionSet)
            {
                foreach (ListItem item in cblSelectionSetElevated.Items)
                {
                    if (item.Value == Selection)
                    {
                        item.Selected = true;
                    }
                }
            }
        }

        /// <summary>
        /// Disables controls when the feature is not loaded on the selected web application. 
        /// </summary>
        private void featureNotLoaded()
        {
            lblErrorMessage.Text = "The custom people editor has not been deployed to this webapplication yet!";
            lblErrorMessage.Visible = true;
            cblSelectionSetCommon.Enabled = false;
            cblSelectionSetElevated.Enabled = false;
            rblAdminType.Enabled = false;
            rblOnlySearchWithinSiteCollection.Enabled = false;
            BtnOK.Enabled = false;
        }
        #endregion
    }
}
